package cluster

import (
	"context"
	"github.com/smallnest/rpcx/server"
	"sync"
)

type ServicePlugin interface{}

type (
	// BackendServicePlugin 后端服务注册插件
	BackendServicePlugin interface {
		RegisterHandler(context.Context, *server.Server, ...string) error
	}

	// GatewayServicePlugin 网关服务注册插件
	GatewayServicePlugin interface {
		RegisterHandler(context.Context, ...string) (GatewayServer, error)
	}
)

type plugins struct {
	mutex   sync.Mutex
	storage []ServicePlugin
}

func (p *plugins) Add(plugin ServicePlugin) {
	p.mutex.Lock()
	defer p.mutex.Unlock()
	p.storage = append(p.storage, plugin)
}

func (p *plugins) GatewayServicePlugin(ctx context.Context, args ...string) (GatewayServer, error) {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	for idx := range p.storage {
		plugin := p.storage[idx]
		if bkplugin, ok := plugin.(GatewayServicePlugin); ok {
			return bkplugin.RegisterHandler(ctx, args...)
		}
	}

	return nil, nil
}

func (p *plugins) BackendServicePlugin(ctx context.Context, s *server.Server, args ...string) error {
	p.mutex.Lock()
	defer p.mutex.Unlock()

	for idx := range p.storage {
		plugin := p.storage[idx]
		if bkplugin, ok := plugin.(BackendServicePlugin); ok {
			if e := bkplugin.RegisterHandler(ctx, s, args...); e != nil {
				return e
			}
		}
	}

	return nil
}
